<template>
  <view class="edit-profile-page">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-button" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="page-title">编辑资料</text>
      <!-- 删除右上角保存按钮 -->
    </view>

    <!-- 头像编辑 -->
    <view class="avatar-section">
      <image
        class="user-avatar"
        :src="formData.avatar || '/static/images/user1.png'"
        mode="aspectFill"
        @click="previewAvatar"
      ></image>
      <view class="avatar-upload" @click="uploadAvatar">
        <text class="upload-text">{{ uploading ? '上传中...' : '更换头像' }}</text>
      </view>
    </view>

    <!-- 表单 -->
    <view class="form-container">
      <view class="form-group">
        <text class="form-label">用户名</text>
        <input 
          class="form-input" 
          v-model="formData.userName" 
          placeholder="请输入用户名"
          maxlength="20"
        />
      </view>

      <view class="form-group">
        <text class="form-label">真实姓名</text>
        <input 
          class="form-input" 
          v-model="formData.name" 
          placeholder="请输入真实姓名"
          maxlength="10"
        />
      </view>

      <view class="form-group">
        <text class="form-label">性别</text>
        <picker 
          class="form-picker" 
          :value="genderIndex" 
          :range="genderOptions" 
          @change="onGenderChange"
        >
          <view class="picker-text">{{ formData.gender || '请选择性别' }}</view>
        </picker>
      </view>

      <view class="form-group">
        <text class="form-label">出生日期</text>
        <picker 
          class="form-picker" 
          mode="date" 
          :value="formData.birthDate" 
          @change="onDateChange"
        >
          <view class="picker-text">{{ formData.birthDate || '请选择出生日期' }}</view>
        </picker>
      </view>

      <view class="form-group">
        <text class="form-label">手机号码</text>
        <input 
          class="form-input" 
          v-model="formData.phone" 
          placeholder="请输入手机号码"
          type="number"
          maxlength="11"
        />
      </view>
    </view>

    <view class="btn-row">
      <button class="reset-btn" @click="onReset">重置</button>
      <button class="save-btn" @click="saveProfile">保存</button>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user.js'

export default {
  data() {
    return {
      formData: {
        userName: '',
        name: '',
        gender: '',
        birthDate: '',
        phone: '',
        avatar: ''
      },
      genderOptions: ['男', '女'],
      genderIndex: 0,
      uploading: false
    }
  },
  
  onLoad() {
    this.loadUserInfo()
  },
  
  onShow() {
    // 每次显示页面时重新加载用户信息
    this.loadUserInfo()
  },
  
  methods: {
    async loadUserInfo() {
      const userId = uni.getStorageSync('userId')
      if (userId) {
        try {
          const res = await getUserInfo(userId)
          if (res && res.code === 1000 && res.data) {
            // 性别映射
            let gender = res.data.gender
            this.formData = { ...this.formData, ...res.data, gender }
            // 设置性别索引
            if (this.formData.gender === '男') {
              this.genderIndex = 0
            } else if (this.formData.gender === '女') {
              this.genderIndex = 1
            }
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
        }
      }
    },
    
    onGenderChange(e) {
      this.genderIndex = e.detail.value
      this.formData.gender = this.genderOptions[this.genderIndex]
    },
    
    onDateChange(e) {
      this.formData.birthDate = e.detail.value
    },
    
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          uni.getFileInfo({
            filePath,
            success: (info) => {
              if (info.size > 5 * 1024 * 1024) {
                uni.showToast({ title: '图片不能超过5MB', icon: 'none' });
                return;
              }
              this.uploading = true;
              uni.uploadFile({
                url: 'http://localhost:7000/user/user/upload',
                filePath,
                name: 'file',
                success: (uploadRes) => {
                  this.uploading = false;
                  let data = uploadRes.data;
                  try { data = JSON.parse(data); } catch(e) {}
                  if (data.code === 1000 && data.data) {
                    this.formData.avatar = data.data;
                    uni.showToast({ title: '上传成功', icon: 'success' });
                  } else {
                    uni.showToast({ title: data.message || '上传失败', icon: 'none' });
                  }
                },
                fail: () => {
                  this.uploading = false;
                  uni.showToast({ title: '上传失败', icon: 'none' });
                }
              });
            }
          });
        }
      })
    },
    previewAvatar() {
      if (this.formData.avatar) {
        uni.previewImage({
          urls: [this.formData.avatar]
        });
      }
    },
    
    validateForm() {
      if (!this.formData.userName.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入真实姓名',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.gender) {
        uni.showToast({
          title: '请选择性别',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.birthDate) {
        uni.showToast({
          title: '请选择出生日期',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }
      
      // 手机号码格式验证
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    async saveProfile() {
      if (!this.validateForm()) {
        return
      }
      try {
        const userId = uni.getStorageSync('userId')
        // birthDate补全T00:00:00，避免后端LocalDateTime解析报错
        const formatDateTime = (dateStr) => {
          if (!dateStr) return '';
          if (dateStr.includes(' ')) return dateStr;
          if (dateStr.includes('T')) return dateStr.replace('T', ' ');
          return dateStr + ' 00:00:00';
        };
        const updateData = {
          userId: userId,
          userName: this.formData.userName,
          name: this.formData.name,
          gender: this.formData.gender, // 直接传“男”或“女”
          birthDate: formatDateTime(this.formData.birthDate),
          phone: this.formData.phone,
          avatar: this.formData.avatar // 关键：加上这一行
        }
        
        const res = await updateUserInfo(updateData)
        if (res && res.code === 1000) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        })
      }
    },

    onReset() {
      this.formData = {
        userName: '',
        name: '',
        gender: '',
        birthDate: '',
        phone: '',
        avatar: ''
      }
      this.genderIndex = 0
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.edit-profile-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  position: relative;
  height: 60px;
  background: linear-gradient(135deg, #5bb8ac 0%, #4a9c91 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
}

.back-button {
  position: absolute;
  left: 20px;
  top: 30px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

.page-title {
  color: #fff;
  font-size: 16px;
  font-weight: bold;
}

.save-button {
  position: absolute;
  right: 20px;
  top: 30px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
}

.save-text {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
  background: #fff;
  margin-bottom: 10px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 15px;
  border: 3px solid #f0f0f0;
}

.avatar-upload {
  padding: 8px 20px;
  background: #5bb8ac;
  border-radius: 20px;
}

.upload-text {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.form-container {
  background: #fff;
  padding: 0 20px;
}

.form-group {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-group:last-child {
  border-bottom: none;
}

.form-label {
  width: 80px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-input {
  flex: 1;
  font-size: 14px;
  color: #333;
  padding: 0;
  border: none;
  background: transparent;
}

.form-picker {
  flex: 1;
}

.picker-text {
  font-size: 14px;
  color: #333;
}

.btn-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 12px;
  margin: 30px 20px;
}

.save-btn, .reset-btn {
  width: 32%;
  padding: 8px 0;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  border: none;
  transition: all 0.2s;
}

.save-btn {
  background: linear-gradient(135deg, #5bb8ac 0%, #4a9c91 100%);
  color: #fff;
}

.save-btn:active {
  background: #4a9c91;
  color: #fff;
}

.reset-btn {
  background: #fff;
  color: #5bb8ac;
  border: 1.5px solid #5bb8ac;
}

.reset-btn:active {
  background: #f0f8f7;
  color: #4a9c91;
  border-color: #4a9c91;
}
</style> 